package com.haiertvbic.tvwa;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.model.ProgramItemBean;
import com.haiertvbic.tvnow.model.SingleHandler;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.service.ServiceUtil;
import com.haiertvbic.tvnow.service.SwitchChanellCallback;
import com.haiertvbic.tvnow.util.AppManager;
import com.haiertvbic.tvnow.util.IsExit;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.ProduceThread;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;

/**
 * 获取节目数据，第二屏
 * 
 * @author sun
 * 
 */
public class TVWAProgramListActivity extends Activity {
	public Activity context = TVWAProgramListActivity.this;
	private static final String TAG = "TVWAProgramListActivity";
	protected static final int GET_PRO_SUC = 01;// 获取节目成功
	protected static final int GET_PRO_FAIL = 02; // 获取节目失败

	private ListView cha_pro_list;
	public static TextView showTime_2;
	public SingleHandler sHandler;
	private ProgressBar bar_on_pro;
	public static View view;

	private int chaId;
	private String chaName;
	private int which;
	private int currentCha = -200;
	private int switchCha = -200;
	private String PRO_TYPE;
	private ArrayList<ProgramBean> programList;
	private boolean canToNext;
	private boolean canSwitch;
	private boolean isHide;
	private Handler myHandler;

	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.acitivity_programs_tvwa);
		view = SetActivityView.setActivityViewTvwa(getWindow(),
				getWindowManager());

		Intent intent = getIntent();
		chaId = intent.getIntExtra("CHA_ID", -1);
		// cha_id= 9;
		chaName = intent.getStringExtra("CHA_NAME");

		initView();
		AppManager.activityList.add(this);

		SLog.d(TAG, "第一屏传来的频道id是：" + chaId);
		getResultPre();
		sHandler = SingleHandler.returnHandler();
		sHandler.setTextView(showTime_2);

		myHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				switch (msg.what) {
				case GET_PRO_FAIL:
					// 获取频道数据失败，消失加载数据进度条
					// progressDialog.dismiss();
					bar_on_pro.setVisibility(View.GONE);
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.get_program_failed));
					break;
				case GET_PRO_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					bar_on_pro.setVisibility(View.GONE);
					if (programList != null && programList.size() > 0) {
						cha_pro_list.setAdapter(new Pro_List_Adapter(
								programList));
					}
					canToNext = true;
					canSwitch = true;
					break;
				case 0:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.read_change_msg_failed));
					break;

				case 4004500:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.change_success));
					currentCha = switchCha;
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {

						SLog.e("", e.toString());
					}
					break;

				case 4004501:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.channel_non_existent));
					break;

				case 4004502:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.please_connect_crb));
					break;

				case 4004503:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.no_set_crb));
					break;

				case -2002:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.connect_break_off));
					break;

				default:
					break;
				}

			}

		};
	}

	@Override
	protected void onPause() {

		super.onPause();
		isHide = true;
	}

	@Override
	protected void onResume() {

		super.onResume();
		if (isHide)
			TVWAMainActivity.fView.setVisibility(View.INVISIBLE);
		if (!ProduceThread.canRun)
			view.setVisibility(View.INVISIBLE);
	}

	/**
	 * 初始化控件
	 */
	private void initView() {

		showTime_2 = (TextView) findViewById(R.id.show_time_2);
		TextView cha_name_te = (TextView) findViewById(R.id.cha_name);
		cha_pro_list = (ListView) findViewById(R.id.cha_pro_list);
		bar_on_pro = (ProgressBar) findViewById(R.id.bar_on_pro);
		cha_name_te.setText(chaName);
		cha_pro_list.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				which = arg2;
				ProduceThread.seconds = 60;
			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		cha_pro_list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				SLog.d(TAG, "在第二界面当前的频道id======" + arg2);
				if (canSwitch && currentCha != chaId) {

					ServiceUtil.changeChannel(context, chaId,
							new SwitchChanellCallback() {

								@Override
								public void returnData(int source,
										int resultCode, int result) {
									myHandler.sendEmptyMessage(resultCode);
								}
							});
					switchCha = chaId;

				}

				ProduceThread.seconds = 60;
			}

		});
	}

	/**
	 * 得到节目的过程，开了一个线程和服务器交互获取数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				bar_on_pro.setVisibility(View.VISIBLE);
				try {
					programList = EPGWeb.getProgramList(context, chaId);
					ArrayList<ProgramItemBean> itemList = EPGWeb
							.getProgramItem(context);
					int size = itemList.size();
					for (int index = 0; index < size; index++) {
						ProgramItemBean itemBean = itemList.get(index);
						if (itemBean.getName().equals("电视剧")) {
							PRO_TYPE = itemBean.getNode() + "";
							SLog.v("lfav", "PRO_TYPE=" + PRO_TYPE);
							break;
						}
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				if (programList != null&&PRO_TYPE!=null) {
					myHandler.sendEmptyMessage(GET_PRO_SUC);
				}else {
					myHandler.sendEmptyMessage(GET_PRO_FAIL);
				}
			};
		}.start();

	}

	/**
	 * 
	 * @author lb
	 * 
	 */
	private class Pro_List_Adapter extends BaseAdapter {
		private List result;

		public Pro_List_Adapter(List result) {
			this.result = programList;
		}

		public int getCount() {
			return programList.size();
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return arg0;
		}

		public View getView(int arg0, View arg1, ViewGroup arg2) {
			SLog.v("lfav", "getView");

			if (arg1 == null) {
				arg1 = LayoutInflater.from(context).inflate(
						R.layout.layout_program_tvwa_item, null);
			}
			TextView pro_name = (TextView) arg1.findViewById(R.id.pro_name);
			TextView tomorrow = (TextView) arg1
					.findViewById(R.id.tomorrow_tvwa);
			TextView pro_time = (TextView) arg1.findViewById(R.id.play_time);
			TextView to_next = (TextView) arg1.findViewById(R.id.toNext);
			ProgramBean p = programList.get(arg0);

			if (p != null) {
				// 只获取当天的节目去掉其他周
				Calendar c = Calendar.getInstance();
				// 得到当前是周几
				int week = c.getTime().getDay();
				if (week == 0) {
					week = 7;
				}
				String s = p.getPstime() + "c";
				s = s.replace(":00c", "");
				if (p.getPweekday() == (week + 1)) {
					tomorrow.setText(context.getResources().getString(
							R.string.tomorrow));
					tomorrow.setVisibility(View.VISIBLE);
					pro_time.setText(s);
				} else {
					tomorrow.setVisibility(View.GONE);
					pro_time.setText(s);
				}
				pro_name.setText(p.getPn());

				if (p.getPtype() != null) {
					if (!p.getPtype().contains(PRO_TYPE)) {
						SLog.v("lfav", arg0 + "条---不是---电视剧");
						to_next.setVisibility(View.INVISIBLE);
					} else {
						SLog.v("lfav", arg0 + "条---是---电视剧");
						to_next.setVisibility(View.VISIBLE);
					}
				}
			}

			return arg1;

		}
	}

	/**
	 * 处理按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		ProduceThread.seconds = 60;
		SLog.d(TAG, "在第二个界面你所按的键值是=====" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			sHandler.setTextView(TVWAMainActivity.showTime_1);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// Toast.makeText(ChannelProActivity.this, "DPAD_BACK",
			// 1000).show();
			ProduceThread.canRun = false;
			ProduceThread.exit = false;
			IsExit.isExit(this);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (programList != null && which < programList.size() && canToNext
					&& programList.size() > 0) {
				String strType = programList.get(which).getPtype();

				if (strType.contains(PRO_TYPE)) {
					Intent intent = new Intent();
					intent.setClass(context, TVWAProgramStateActivity.class);
					intent.putExtra("PRO_ID", programList.get(which).getPid());
					intent.putExtra("PRO_NAME", programList.get(which).getPn());
					startActivity(intent);
					view.setVisibility(View.INVISIBLE);
				} else {
					LocateToast
							.locateToast(
									this,
									200,
									getResources()
											.getString(
													R.string.the_pro_is_not_Television_poly));

				}
			}

		}
		return super.onKeyDown(keyCode, event);
	}

}
